package org.arch_learn.orm_starter.auto_config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.arch_learn.flashboot.autoconfigure.Bean;
import org.arch_learn.flashboot.autoconfigure.Configuration;
import org.arch_learn.flashboot.autoconfigure.EnableConfigurationProperties;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {

    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) throws PropertyVetoException {
        return createDataSource(dataSourceProperties);
    }

    private DataSource createDataSource(DataSourceProperties dataSourceProperties) throws PropertyVetoException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(dataSourceProperties.getDriver());
        comboPooledDataSource.setJdbcUrl(dataSourceProperties.getJdbcUrl());
        comboPooledDataSource.setUser(dataSourceProperties.getUsername());
        comboPooledDataSource.setPassword(dataSourceProperties.getPassword());
        return comboPooledDataSource;
    }
}
